<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>打字机</title>
    <style type="text/css">
        .mybox {
            height: 40px;
            border: 5px solid #ddd;
            font-size: 25px;
        }
    </style>
    <script>
        function random() {
            return Math.random() * 255;
        };
        window.addEventListener('load', function() {
            var i = 0; //计数器控制text的索引号
            var mybox = document.querySelector('.mybox'); //获取元素
            var text = '两只老虎，两只老虎';
            setInterval(function() {
                if (mybox.innerHTML !== '') { //div内容不为空是执行，防止无span时执行报错
                    var spans = document.querySelectorAll('span'); //获取当前所有span
                    if (spans.length == text.length) { //如果span个数跟text文本个数一样，证明text文本全部输出完毕
                        mybox.innerHTML = ''; //清空div内容
                        i = 0; //计数器重新开始
                    };
                };
                mybox.innerHTML = mybox.innerHTML + '<span style="color: rgb(' + random() + ',' + random() + ',' + random() + ');">' + text.substr(i++, 1) + '</span>';
            }, 300)
        });
    </script>

</head>

<body>
    <div class="mybox"></div>
</body>

</html>